package own.stu.jobgib.playown.redis.redisson;

import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import static own.stu.jobgib.playown.redis.redisson.AllS.dealBusiness;

@Slf4j
public class Scheduled {

    public static void main(String[] args) throws InterruptedException {

        monitorDnsChange();
        TimeUnit.MINUTES.sleep(2);
    }

    private static NioEventLoopGroup group = null;

    static {
        group = new NioEventLoopGroup(4, new DefaultThreadFactory("redisson-netty"));
    }

    private static final ThreadLocalRandom random = ThreadLocalRandom.current();

    private static void monitorDnsChange() {
        // schedule 只是延迟某个时间 丢一个任务到队列中
        // whenComplete 可以再次发起该monitorDnsChange动作触发
        group.schedule(() -> {

            CompletableFuture<Integer> mf = dealBusiness("master");
            CompletableFuture<Integer> sf = dealBusiness("slaves");
            CompletableFuture.allOf(mf, sf)
                    .thenAccept((v) -> {
                        log.info("{} - [{}] done", new Date(), Thread.currentThread().getName());
                    })
                    .whenComplete((r, e) -> monitorDnsChange());
        }, 2000, TimeUnit.MILLISECONDS);
    }
}
